Key to CSE142 Midterm, Winter 2014 1. Expression Value ----------------------------------------------- 20 - 11 / 2 * 3 5 67 % 10 - 15 % 4 + 3 % 8 7 2 + 2 * 7 + "." + (2 + 5) + 3 "16.73" 3.5 * 2 * 3 / 2 + 13 / 3 14.5 107 / 10 * 2 / 4 / 2.0 + 6 / 4.0 4.0 2. Parameter Mystery. The program produces the following output. ham eats the train in the rain house eats the rain in the train sam eats the house in the green fox eats the mouse in the house 3. Method Call Output Produced --------------------------------------- ifElseMystery(2, 7); 11 7 ifElseMystery(6, 6); 6 16 ifElseMystery(4, -1); 3 0 ifElseMystery(11, 10); 11 21 4. Method Call Output Produced --------------------------------------- mystery(6, 0); 0 mystery(8, 1); 0, 8 mystery(3, 3); 0, 3, 9, 17 mystery(4, 2); 0, 4, 10 5. x < y z == 0 z % 2 == 0 +---------------------+---------------------+---------------------+ Point A | sometimes | always | always | +---------------------+---------------------+---------------------+ Point B | always | sometimes | sometimes | +---------------------+---------------------+---------------------+ Point C | sometimes | never | always | +---------------------+---------------------+---------------------+ Point D | sometimes | never | never | +---------------------+---------------------+---------------------+ Point E | never | sometimes | sometimes | +---------------------+---------------------+---------------------+ 6. One of many possible solutions appears below: public static boolean hasConsecutive(Scanner s) { System.out.print("Type 3 ints: "); int n1 = s.nextInt(); int n2 = s.nextInt(); int n3 = s.nextInt(); return Math.abs(n1 - n2) == 1 || Math.abs(n2 - n3) == 1 || Math.abs(n3 - n1) == 1; } 7. One possible solution appears below: public static int maxSevens(Random r, int times) { int max = 0; int sevens = 0; for (int i = 0; i < times; i++) { int num = r.nextInt(6) + 5; System.out.print(num + " "); if (num == 7) { sevens++; if (sevens > max) { max = sevens; } } else { sevens = 0; } } System.out.println(); System.out.println("Run of " + max + " sevens in " + times + " tries."); return max; } 8. Three possible solutions appear below: public static int collapseDigits(int value) { int result = 0; int place = 0; while (value > 0) { result += value % 10 * Math.pow(10, place); if (value % 10 == value % 100 / 10) { value /= 100; } else { value /= 10; } place++; } return result; } public static int collapseDigits(int value) { int result = 0; int count = 0; int prev = -1; while (value > 0) { int digit = value % 10; value = value / 10; if (digit != prev) { result += digit * Math.pow(10, count); count++; prev = digit; } } return result; } public static int collapseDigits(int n) { int result = 0; int place = 0; while (n >= 10) { int digit = n % 10; int rest = n / 10; if (digit == rest % 10) { n = rest / 10; } else { n = rest; } result += Math.pow(10, place) * digit; place++; } result += Math.pow(10, place) * n; return result; }